/**
 *@ClassName receiveMsg
 *@Description  用于消息发送
 *@Author JiJiang
 *@Date 2022/10/2 17:16

 /**
 * webSocket连接对象
 */
let webSocket;

$(function () {

    //监听窗口的关闭事件
    window.onbeforeunload = function () {
        if (webSocket != null) {
            webSocket.close();
        }
    }

});

/**
 * 创建一个websocket对象，并绑定其所有的监听事件
 * @param onopen
 * @param onerror
 * @param onclose
 * @param onmessage
 */
function createAWebSocketBindAll(
    onopen = (event) => {
        console.log("与服务器的websocket连接建立成功！ event =", event);
    }
    , onerror = (event) => {
        console.error("与服务器的websocket连接出现错误，原因如下：\r\n event=", event)
    }
    , onclose = (event) => {
        console.log("与服务器的websocket连接建立成功event =", event);
        console.warn("与服务器的websocket连接断开！event =", event)
    }
    , onmessage = (event) => {
        console.debug("服务器发送消息过来了！ event =", event);
    }) {
    //获取登录的用户名
    let loginUserName = localStorage.getItem(USERNAME_KEY_LOGIN_LOCALSTORAGE);

    //如果用户名为空，直接退出
    if (loginUserName == null || loginUserName == "") return;

    //建立连接
    webSocket = new WebSocket(`${HOST_WEBSOCKET}/${loginUserName}`);
    //绑定事件
    webSocket.onopen = onopen;
    webSocket.onerror = onerror;
    webSocket.onclose = onclose;
    webSocket.onmessage = onmessage;
}


/**
 * 创建一个websocket对象，并绑定其消息接收的事件
 * @param msgListen
 */
function createAWebSocketBindOnMsg(msgListen = (event) => {
}) {
    createAWebSocketBindAll(undefined, undefined, undefined, msgListen);
}


